package gameEngine;


import exceptions.IncorrectInputException;
import exceptions.NullFieldException;

public class GameField {

	private static final int MIN_BOARD_SIZE = 2;
	static Dot[][] gameField;
	private static char[][] printField; 

	
	
	/**
	 * This is the "constructor" of this class. It sets the field size.
	 * 
	 * @param fieldSize - the game field size.
	 * @throws NullFieldException - if the size is less than Minimum board size e.g. 2;
	 * @throws IncorrectInputException 
	 */
	
	public static void setGameField(int fieldSize) throws NullFieldException, IncorrectInputException {
		if (fieldSize > MIN_BOARD_SIZE) {
			gameField = new Dot[fieldSize][fieldSize];
			
			int PRINTFIELD_SIZE = gameField.length * 2 - 1;
			
			printField = new char[PRINTFIELD_SIZE][PRINTFIELD_SIZE];
			/*
			 * The gameField elements will be null. Populate them with Dots.
			 */
			populateFieldWithDots();
		}else{
			throw new NullFieldException("The board can't be that small.");
		}
	}
	
	/**
	 * This method is called in the constructor to populate the 
	 * array holding dots. Otherwise they will be null.
	 * @throws IncorrectInputException 
	 */
	private static void populateFieldWithDots() throws IncorrectInputException {
		for (int row = 0; row < gameField.length; row++) {
			for (int col = 0; col < gameField[row].length; col++) {
				gameField[row][col] = new Dot(row, col);
			}
		}
	}

	

	/**
	 * Convert from Array with dot objects to Human-readable array.
	 * @throws NullFieldException  If the field array is Null.
	 */
	public static void populatePrintFieldArray() throws NullFieldException {
		if (gameField == null) throw new NullFieldException("The game field is null.");
	
	
		for(int i = 0; i < printField.length; i++)
			for(int j = 0; j < printField[i].length; j++) 
				if(i % 2 == 0 && j % 2 == 0) 
					printField[i][j] = '.';
		
		for(int row = 0;row<gameField.length;row++){
			for(int col = 0;col<gameField[row].length-1;col++){
				if(gameField[row][col].getRightLine()!=null){
					printField[row*2][col*2+1] = '-';
				}
				if(gameField[row][col].getUpLine()!=null){
					printField[row*2-1][col*2] = '|';
				}
			}
		}
	}
 /**
  * Prints the dots and lines on screen.
  * @throws NullFieldException  If the field array is Null.
  */
	public static void printField() throws NullFieldException {
		if(printField == null)  throw new NullFieldException("The game field is null.");
		
		for(int row = 0;row<printField.length;row++){
			for(int col = 0;col<printField[row].length;col++){
				System.out.print(printField[row][col]);
			}
			System.out.println();
		}
	}
}
